package org.esir.base.android.thread

import android.os.Handler
import android.os.Looper
import android.os.Message
import io.esirong.thread.PlatformThread
import org.esir.base.android.thread.MESSAGE_POST_RESULT.MSG_WHAT_RUNNABLE

/**(Android)
 * @ClassName: AndroidMain
 * @Description: android 平台主线程调度
 * @author: huangrongcai
 * @date: 2022/9/6
 *
 */
class AndroidMain : PlatformThread {
    private val sHandler: InternalHandler = InternalHandler(Looper.getMainLooper())
    override fun run() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun cancel(runnable: Runnable?) {
        getMainHandler().removeCallbacks(runnable)
    }

    override fun execute(runnable: Runnable?) {
        if (runnable == null) {
            return
        }
        if (Looper.getMainLooper().thread === Thread.currentThread()) {
            runnable.run()
        } else {
            var message = getMainHandler().obtainMessage(MSG_WHAT_RUNNABLE,
                    runnable)
            message?.sendToTarget()
        }
    }

    private fun getMainHandler(): Handler {
        synchronized(AndroidMain::class.java) {
            return sHandler
        }
    }

    //通过Handler机制，把任务抛给了主线程。
    companion object

    class InternalHandler(looper: Looper?) : Handler(looper) {

        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MSG_WHAT_RUNNABLE -> {
                    val result = msg.obj as Runnable
                    //通过handler机制，回到主线程，调用finish函数
                    result.run()
                }
                else -> {
                    dispatchMessage(msg)
                }
            }
        }
    }
}

object MESSAGE_POST_RESULT {
    /**
     * 主线事件消息
     */
    const val MSG_WHAT_RUNNABLE = 0XFFFF - 1
}
